//
//  XCStatusPictureView.swift
//  小陈微博Swift用纯代码创建
//
//  Created by 小陈 on 16/3/4.
//  Copyright © 2016年 小陈. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
/// 最大的列数
private let Maxcloumn = 3
/// cell 之间的间距
private let XCStatusPictureCellMargin :CGFloat = 10
/// cell 的宽高
private let XCStatusPictureCellWH = (UIScreen.width - 2 * XCStatusPictureCellMargin - (CGFloat(Maxcloumn) - 1) * XCStatusPictureCellMargin) / CGFloat(Maxcloumn)
/// cellSize
private let XCStatusPictureCellSize = CGSizeMake(XCStatusPictureCellWH , XCStatusPictureCellWH)


let ReuseIdentifier = "ReuseIdentifier"

class XCStatusPictureView: UICollectionView {
    /// 获取微博数据
    var status: XCStatus?{// 微博数据可能为 nil
        didSet{
  
           let viewSize = calcViewSize()
           
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(viewSize)
            }
            // 刷新collectionView
            self.reloadData()
        }
    }
    
    
    //计算微博配图的大小
    func calcViewSize() -> CGSize{
        let count = self.status?.storePictureURLs?.count ?? 0

        // 当没有图片的时候返回 零
        if count == 0 {
            return CGSizeZero
        }
       
        if count == 1 {
            var size = CGSizeMake(180, 100)
            

 
//            
    let imageURLString = status?.storePictureURLs?.first?.absoluteString
            
    print("imageURLString: \(imageURLString)")
            if let image = SDImageCache.sharedImageCache().imageFromMemoryCacheForKey(imageURLString!){
            
//            image.imageWithRenderingMode(UIImageRenderingMode.Automatic)
                
//                UIScreen
                size = image.size
                
//                print("image.size\(image.size)")
            }
            if size.width < 40 {
                size.width = 40
            }
            if size.width > UIScreen.width * 0.5{
                size.width = UIScreen.width * 0.5
            }
            
//            if size.height < 40{
//                
//                size.height = 100
//            }
       
            Flowlayout.itemSize = size
            Flowlayout.minimumInteritemSpacing = 0
            Flowlayout.minimumLineSpacing = 0
//
            
            return size
        }
        
        
        Flowlayout.itemSize = XCStatusPictureCellSize
        Flowlayout.minimumInteritemSpacing = XCStatusCellMargin
        Flowlayout.minimumLineSpacing = XCStatusCellMargin
        
         // 假设图片是两列的时候
        var column = Maxcloumn
        if count == 2 || count == 4 { // 当图片的个数是2 张或者 4 张的时候 显示两列
            column = 2
        }


    
        let row = (count + Maxcloumn - 1) / Maxcloumn
        
        let width = CGFloat(column) * XCStatusPictureCellWH + CGFloat(column - 1) * XCStatusPictureCellMargin
        
        let height = CGFloat(row) * XCStatusPictureCellWH + CGFloat(row - 1) * XCStatusPictureCellMargin
//
//        print( "count\(count) column\(column) row\(row) width \(width) height \(height)")
 
        
        return CGSizeMake(width, height)
        
  
    }
    
    
    
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    let Flowlayout = UICollectionViewFlowLayout()
    

    init(){
        
        super.init(frame:CGRectZero , collectionViewLayout: Flowlayout)
        
             backgroundColor = UIColor.clearColor()
      // 注册 collectioViewcell

        self.delegate = self
        self.dataSource = self

        self.registerClass(XCStatusPritureCell.self, forCellWithReuseIdentifier: ReuseIdentifier)

    
    }
   
    
  
}
extension XCStatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate {
    
  
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return status?.pic_urls!.count ?? 0

    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! XCStatusPritureCell

        let url = status!.storePictureURLs?[indexPath.item]


      cell.imageUrl = url
        return cell
    }
}



class XCStatusPritureCell: UICollectionViewCell {

    var imageUrl:NSURL?{
        didSet{
          bgImageView.sd_setImageWithURL(imageUrl)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
      prepareUI()
    }
    
    func prepareUI(){
        contentView.addSubview(bgImageView)
        
       bgImageView.snp_makeConstraints(closure: { (make) -> Void in
          make.edges.equalTo(contentView)
       })
        
        
 
    }
    
    // 背景图片
   lazy var bgImageView: UIImageView = UIImageView(image:nil)
    
}